package com.gusha.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.gusha.dao.SysLogErrorDao;
import com.gusha.model.SysLogError;
import com.gusha.utils.DateUtils;

@Component
public class CommonExceptionHandler implements HandlerExceptionResolver {
	
	private static Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @Autowired
    private SysLogErrorDao sysLogErrorDao;
    
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2,Exception ex) {
		ModelAndView modelAndView = new ModelAndView("redirect:/to500");

        try {
			/* 错误日志输出到控制台和文件 */
			Writer result = new StringWriter();
			PrintWriter printWriter = new PrintWriter(result);
			ex.printStackTrace(printWriter);
			log.error(result.toString());
			printWriter.flush();
			printWriter.close();
			
			/* 错误日志入库 */
			//获取请求的URL  
			String url = request.getRequestURI();
			if(url != null){
				SortedMap<Object,Object> mapRequest = new TreeMap<Object,Object>();   
			    Enumeration<String> paramNames = request.getParameterNames();  
			    while (paramNames.hasMoreElements()) {  
			        String paramName = (String) paramNames.nextElement();  
			        String[] paramValues = request.getParameterValues(paramName);  
			        if (paramValues.length == 1) {  
			            String paramValue = paramValues[0];  
			            if (paramValue.length() != 0) {  
			            	mapRequest.put(paramName, paramValue);  
			            }  
			        }  
			    }
			    String params = "";
				for (Map.Entry<Object, Object> entry : mapRequest.entrySet()) {
					String key = entry.getKey().toString();
					String value = entry.getValue().toString();
					params += key+"："+value+"==";
				}
				
				SysLogError sysLogError = new SysLogError();
				sysLogError.setPath(url);
				sysLogError.setParams(params);
				sysLogError.setExceptionInfo(result.toString());
				sysLogError.setCreateTime(DateUtils.getNow());
				sysLogErrorDao.saveAndFlush(sysLogError);
			}
			result.flush();
			result.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return modelAndView;
	}

   
}
